using Microsoft.EntityFrameworkCore;
using WeatherSystem.API.Data;
using WeatherSystem.API.Models;
using System.Text.Json;

namespace WeatherSystem.API.Services
{
    /// <summary>
    /// 指标配置服务接口
    /// </summary>
    public interface IMetricConfigurationService
    {
        Task<List<Models.MetricDefinition>> GetAvailableMetricsAsync();
        Task<PagedResult<Models.MetricDefinition>> GetAvailableMetricsAsync(int page, int pageSize, bool? isActive = null);
        Task<List<string>> GetCityMetricsAsync(Guid cityId);
        Task<List<Models.MetricDefinition>> GetEnabledMetricsForCityAsync(Guid cityId);
        Task SetCityMetricsAsync(Guid cityId, List<string> metricKeys);
        Task<Dictionary<string, object>> GetGlobalMetricConfigAsync();
        Task SetGlobalMetricConfigAsync(Dictionary<string, object> config);
        Task<List<Models.MetricDefinition>> GetDefaultMetricsAsync();
    }

    /// <summary>
    /// 指标配置服务实现
    /// </summary>
    public class MetricConfigurationService : IMetricConfigurationService
    {
        private readonly WeatherDbContext _context;
        private readonly ILogger<MetricConfigurationService> _logger;

        public MetricConfigurationService(
            WeatherDbContext context,
            ILogger<MetricConfigurationService> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有可用的指标定义
        /// </summary>
        public async Task<List<Models.MetricDefinition>> GetAvailableMetricsAsync()
        {
            var config = await GetConfigurationAsync("AvailableMetrics");
            if (config?.ConfigValue != null)
            {
                try
                {
                    var metrics = JsonSerializer.Deserialize<List<Models.MetricDefinition>>(config.ConfigValue);
                    return metrics ?? GetHardcodedMetrics();
                }
                catch (JsonException ex)
                {
                    _logger.LogWarning(ex, "解析可用指标配置失败，使用默认配置");
                }
            }

            // 返回默认指标配置
            var defaultMetrics = GetHardcodedMetrics();
            await SetAvailableMetricsAsync(defaultMetrics);
            return defaultMetrics;
        }

        /// <summary>
        /// 获取指定城市启用的指标
        /// </summary>
        public async Task<List<string>> GetCityMetricsAsync(Guid cityId)
        {
            var config = await GetConfigurationAsync($"CityMetrics_{cityId}");
            if (config?.ConfigValue != null)
            {
                try
                {
                    var metrics = JsonSerializer.Deserialize<List<string>>(config.ConfigValue);
                    return metrics ?? new List<string>();
                }
                catch (JsonException ex)
                {
                    _logger.LogWarning(ex, "解析城市指标配置失败，城市ID: {CityId}", cityId);
                }
            }

            // 返回默认指标
            var defaultMetrics = await GetDefaultMetricsAsync();
            var defaultMetricKeys = defaultMetrics.Select(m => m.Key).ToList();
            
            // 自动设置默认配置
            await SetCityMetricsAsync(cityId, defaultMetricKeys);
            return defaultMetricKeys;
        }

        /// <summary>
        /// 获取指定城市启用的指标定义
        /// </summary>
        public async Task<List<Models.MetricDefinition>> GetEnabledMetricsForCityAsync(Guid cityId)
        {
            var enabledMetricKeys = await GetCityMetricsAsync(cityId);
            var availableMetrics = await GetAvailableMetricsAsync();
            
            return availableMetrics
                .Where(m => enabledMetricKeys.Contains(m.Key))
                .ToList();
        }

        /// <summary>
        /// 设置指定城市的指标配置
        /// </summary>
        public async Task SetCityMetricsAsync(Guid cityId, List<string> metricKeys)
        {
            // 验证城市是否存在
            var cityExists = await _context.Cities.AnyAsync(c => c.Id == cityId);
            if (!cityExists)
            {
                throw new ArgumentException($"城市不存在: {cityId}");
            }

            // 验证指标是否有效
            var availableMetrics = await GetAvailableMetricsAsync();
            var availableKeys = availableMetrics.Select(m => m.Key).ToHashSet();
            var invalidKeys = metricKeys.Where(k => !availableKeys.Contains(k)).ToList();
            if (invalidKeys.Any())
            {
                throw new ArgumentException($"无效的指标配置: {string.Join(", ", invalidKeys)}");
            }

            var configKey = $"CityMetrics_{cityId}";
            var configValue = JsonSerializer.Serialize(metricKeys);

            await SetConfigurationAsync(configKey, configValue, $"城市 {cityId} 的指标配置");
            
            _logger.LogInformation("已更新城市指标配置，城市ID: {CityId}, 指标数量: {Count}", 
                cityId, metricKeys.Count);
        }

        /// <summary>
        /// 获取全局指标配置
        /// </summary>
        public async Task<Dictionary<string, object>> GetGlobalMetricConfigAsync()
        {
            var config = await GetConfigurationAsync("GlobalMetricConfig");
            if (config?.ConfigValue != null)
            {
                try
                {
                    var globalConfig = JsonSerializer.Deserialize<Dictionary<string, object>>(config.ConfigValue);
                    return globalConfig ?? new Dictionary<string, object>();
                }
                catch (JsonException ex)
                {
                    _logger.LogWarning(ex, "解析全局指标配置失败");
                }
            }

            // 返回默认全局配置
            var defaultConfig = new Dictionary<string, object>
            {
                { "defaultCollectionInterval", 30 },
                { "enableDynamicMetrics", true },
                { "metricValidationEnabled", true },
                { "maxMetricsPerCity", 20 }
            };

            await SetGlobalMetricConfigAsync(defaultConfig);
            return defaultConfig;
        }

        /// <summary>
        /// 设置全局指标配置
        /// </summary>
        public async Task SetGlobalMetricConfigAsync(Dictionary<string, object> config)
        {
            var configValue = JsonSerializer.Serialize(config);
            await SetConfigurationAsync("GlobalMetricConfig", configValue, "全局指标配置");
            
            _logger.LogInformation("已更新全局指标配置，配置项数量: {Count}", config.Count);
        }

        /// <summary>
        /// 获取分页的可用指标定义
        /// </summary>
        public async Task<PagedResult<Models.MetricDefinition>> GetAvailableMetricsAsync(int page, int pageSize, bool? isActive = null)
        {
            var query = _context.MetricDefinitions.AsQueryable();

            if (isActive.HasValue)
            {
                query = query.Where(m => m.IsActive == isActive.Value);
            }

            var totalCount = await query.CountAsync();

            var metrics = await query
                .OrderBy(m => m.DisplayOrder)
                .ThenBy(m => m.Name)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .AsNoTracking()
                .ToListAsync();

            return new PagedResult<Models.MetricDefinition>
            {
                Data = metrics,
                TotalCount = totalCount,
                Page = page,
                PageSize = pageSize
            };
        }

        /// <summary>
        /// 获取默认启用的指标
        /// </summary>
        public async Task<List<Models.MetricDefinition>> GetDefaultMetricsAsync()
        {
            var availableMetrics = await GetAvailableMetricsAsync();
            return availableMetrics.Where(m => m.IsDefault).ToList();
        }

        /// <summary>
        /// 设置可用指标定义
        /// </summary>
        private async Task SetAvailableMetricsAsync(List<Models.MetricDefinition> metrics)
        {
            var configValue = JsonSerializer.Serialize(metrics);
            await SetConfigurationAsync("AvailableMetrics", configValue, "可用指标定义");
        }

        /// <summary>
        /// 获取配置
        /// </summary>
        private async Task<SystemConfiguration?> GetConfigurationAsync(string configKey)
        {
            return await _context.SystemConfigurations
                .FirstOrDefaultAsync(c => c.ConfigKey == configKey);
        }

        /// <summary>
        /// 设置配置
        /// </summary>
        private async Task SetConfigurationAsync(string configKey, string configValue, string description)
        {
            var config = await GetConfigurationAsync(configKey);
            
            if (config == null)
            {
                config = new SystemConfiguration
                {
                    Id = Guid.NewGuid(),
                    ConfigKey = configKey,
                    ConfigValue = configValue,
                    Description = description,
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                };
                _context.SystemConfigurations.Add(config);
            }
            else
            {
                config.ConfigValue = configValue;
                config.UpdatedAt = DateTime.UtcNow;
            }

            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 获取硬编码的指标定义（兼容现有数据）
        /// </summary>
        private static List<Models.MetricDefinition> GetHardcodedMetrics()
        {
            return new List<Models.MetricDefinition>
            {
                new Models.MetricDefinition
                {
                    Key = "temperature",
                    Name = "温度",
                    Unit = "°C",
                    Description = "环境温度",
                    DataType = "decimal",
                    IsDefault = true,
                    ValidationRules = "{\"MinValue\": -50, \"MaxValue\": 60}"
                },
                new Models.MetricDefinition
                {
                    Key = "humidity",
                    Name = "湿度",
                    Unit = "%",
                    Description = "相对湿度",
                    DataType = "decimal",
                    IsDefault = true,
                    ValidationRules = "{\"MinValue\": 0, \"MaxValue\": 100}"
                },
                new Models.MetricDefinition
                {
                    Key = "pressure",
                    Name = "气压",
                    Unit = "hPa",
                    Description = "大气压强",
                    DataType = "decimal",
                    IsDefault = true,
                    ValidationRules = "{\"MinValue\": 900, \"MaxValue\": 1100}"
                },
                new Models.MetricDefinition
                {
                    Key = "windSpeed",
                    Name = "风速",
                    Unit = "m/s",
                    Description = "风速",
                    DataType = "decimal",
                    IsDefault = true,
                    ValidationRules = "{\"MinValue\": 0, \"MaxValue\": 100}"
                },
                new Models.MetricDefinition
                {
                    Key = "windDirection",
                    Name = "风向",
                    Unit = "°",
                    Description = "风向角度",
                    DataType = "decimal",
                    IsDefault = false,
                    ValidationRules = "{\"MinValue\": 0, \"MaxValue\": 360}"
                },
                new Models.MetricDefinition
                {
                    Key = "visibility",
                    Name = "能见度",
                    Unit = "km",
                    Description = "大气能见度",
                    DataType = "decimal",
                    IsDefault = false,
                    ValidationRules = "{\"MinValue\": 0, \"MaxValue\": 50}"
                },
                new Models.MetricDefinition
                {
                    Key = "uvIndex",
                    Name = "紫外线指数",
                    Unit = "",
                    Description = "紫外线强度指数",
                    DataType = "decimal",
                    IsDefault = false,
                    ValidationRules = "{\"MinValue\": 0, \"MaxValue\": 15}"
                },
                new Models.MetricDefinition
                {
                    Key = "weatherCondition",
                    Name = "天气状况",
                    Unit = "",
                    Description = "天气描述",
                    DataType = "string",
                    IsDefault = true,
                    ValidationRules = "{\"MaxLength\": 100}"
                }
            };
        }
    }
}